<template>
  <div>
    <el-dialog
      title="编辑安装点"
      :visible.sync="dialogVisible"
      width="620px"
      :before-close="closeEditDialog"
      :close-on-click-modal="false"
      :modal-append-to-body="false"
    >
      <el-form
        :model="getLocationInfo"
        :rules="rules"
        ref="refEditInfo"
        label-width="100px"
      >
        <el-form-item
          size="small"
          label="安装点名称"
          placeholder="请输入"
          prop="name"
        >
          <el-input
            clearable
            v-model="getLocationInfo.name"
            maxlength="20"
          ></el-input>
        </el-form-item>

        <!-- <el-form-item size="small" label="详细地址" prop="address">
          <el-input type="textarea" :rows="2" placeholder="请输入详细地址" maxlength="100" v-model="getLocationInfo.address">
          </el-input>
        </el-form-item> -->

        <el-form-item size="small" label="安装点照片" prop="pic">
          <el-upload
            :class="{ disabled: uploadDisabled }"
            :on-remove="handleRemove"
            :on-change="uploadSectionFile"
            :action="baseUrl"
            list-type="picture-card"
            accept=".jpg,.png"
            :on-preview="handlePictureCardPreview"
            :headers="headers"
            :before-upload="beforeAvatarUpload"
            :on-success="handleSuccessFunction"
            :limit="6"
            :on-exceed="handleExceedScene"
            :file-list="fileList"
            :on-error="uploadFileError"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>

        <!-- <el-form-item size="small" label="接警人">
          <el-select v-model="editInfo.alarmReceiverIdList" filterable multiple :multiple-limit="6" placeholder="请选择接警人"
            style="width: 100%">
            <el-option v-for="item in dataList" :key="item.id" :label="item.name+'：'+item.mobile" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item> -->
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeEditDialog" class="cancel-button">取 消</el-button>
        <el-button
          size="small"
          @click="editSubmit"
          v-preventReClick="1000" class="confirm-button"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <el-dialog :visible.sync="dialogVisible2">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
import {
  reqAlarmReceiverList,
  reqUpdateFloor,
  reqAddReceiver,
} from "@/api/api";
import asc from "@utils/asc.js"; //加密解密
import { mapState } from "vuex";

export default {
  name: "editTeacherMemebr",
  props: ["getLocationInfo", "picList2", "result", "arr"],
  data() {
    return {
      dataList: [],
      fileList: [],
      headers: {
        token: asc.decrypt(sessionStorage.getItem("token")),
      },
      editInfo: {
        alarmReceiverIdList: [],
      },
      dialogImageUrl: "",
      dialogVisible2: false,
      picList: [],
      dialogVisible: false,
      // 表单验证规则
      rules: {
        name: [
          {
            required: true,
            message: "请输入安装点名称",
            trigger: "blur",
          },
        ],
        address: [
          {
            required: true,
            message: "请输入详细地址",
            trigger: "blur",
          },
        ],
      },
      uploadDisabled: false, //加号默认显示
    };
  },
  watch: {
    dialogVisible: {
      handler(val) {
        if (val) {
          this.fileList = [];
          this.picList = [];
          this.picList2.forEach((item) => {
            this.fileList.push({ url: item });
            this.picList.push(item);
          });
          // console.log(this.picList2.length);
          if (this.picList2.length >= 6) {
            this.uploadDisabled = true; //隐藏加号
          }
          // 接警人默认选中已有的
          this.editInfo.alarmReceiverIdList = [];
          this.arr.forEach((item) => {
            this.editInfo.alarmReceiverIdList.push(item.id);
          });
        }
      },
    },
  },
  computed: {
    ...mapState(["user"]),
  },
  methods: {
    uploadSectionFile(file, fileList) {
      if (fileList.length >= 6) {
        this.uploadDisabled = true; //隐藏加号
      }
    },
    //上传失败
    uploadFileError(err, file, fileList) {
      this.uploadDisabled = false;
    },
    //删除照片
    handleRemove(file, fileList) {
      // console.log(fileList);
      this.picList = [];
      fileList.forEach((item) => {
        if (item.response) {
          this.picList.push(item.response.data.url);
        } else {
          this.picList.push(item.url);
        }
      });
      setTimeout(() => {
        this.uploadDisabled = false;
      }, 1000);
    },
    // 获取接警人列表
    async getDataList() {
      const res = await reqAlarmReceiverList(1, 100, {
        userId: this.user.userId,
        roleName: this.user.roleName,
        orgId: this.result.orgId,
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      // console.log(res);
      this.dataList = res.data.rows;
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible2 = true;
    },
    // 上传文件之前的钩子
    beforeAvatarUpload(file) {
      let isJPG = true;
      if (file.type !== "image/png" && file.type !== "image/jpeg") {
        this.$message.error("图片只能是 jpg/png 格式!");
        isJPG = false;
      }
      let isLt = file.size / 1024 < 20000; // 判断是否小于500Kb  500
      if (!isLt) {
        this.$modal.notifyWarning("图片大小不能超过20MB! 请重新上传");
        this.uploadDisabled = false;
        isJPG = false;
      }
      return isJPG;
    },
    // 上传成功
    handleSuccessFunction(response, file, fileList) {
      this.picList.push(file.response.data.url);
    },
    // 文件超出个数限制时的钩子
    handleExceedScene() {
      this.$modal.notifyWarning(`安装点照片最多6张`);
    },
    // 点击修改
    editSubmit() {
      this.$refs.refEditInfo.validate(async (valid) => {
        if (valid) {
          const res = await reqUpdateFloor({
            id: this.getLocationInfo.id,
            name: this.getLocationInfo.name,
            picList: this.picList,
          });
          if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
          this.$modal.notifySuccess("编辑安装点成功");
          this.$emit("getedit", this.getLocationInfo);
          this.$parent.GetPicBySpaceId(); //更新照片
          this.dialogVisible = false;
          this.fileList = [];

          // 接警人
          // const res2 = await reqAddReceiver({
          //   spaceId: this.result.id,
          //   alarmReceiverIdList: this.editInfo.alarmReceiverIdList,
          // });
          // if (res2.code !== 20000)
          //   return this.$modal.notifyWarning(res2.message);
          // this.$modal.notifySuccess("新增接警人成功");
          // this.$parent.getByTargetId();
          this.editInfo.alarmReceiverIdList = [];
        }
      });
    },
    // 点击关闭弹框
    closeEditDialog() {
      this.fileList = [];
      this.$refs.refEditInfo.resetFields();
      // this.selectedProvinceCityArea = [];
      this.dialogVisible = false;
    },
  },
  created() {
    this.baseUrl = `${this.$baseURL_copy}file/upload`;
  },
  deactivated() {
    if(this.$refs.refEditInfo!=null){
      this.closeEditDialog();
    }
    this.dialogVisible2 = false;
  },
};
</script>

<style lang="less" scoped>
@import url("../../common.less");

.mapLoc {
  height: 100vh;
  width: 100vw;
  position: fixed;
  z-index: 9999;
  top: 0;
  left: 0;

  .iframe {
    width: 100%;
    height: 100%;
  }
}
// 隐藏加号
/deep/ .disabled .el-upload--picture-card {
  display: none !important;
}
</style>